package es.index.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class BytesUtil {
	private BytesUtil() {
	}

	/**
	 * 从输入流中读取指定长度的字符串
	 * 
	 * @param _input
	 *            输入流
	 * @param size
	 *            需要读取的长度
	 * @return String
	 */
	public static String getInputStreamByString(InputStream _input, int size) {
		try {
			byte[] bytes = new byte[size];
			_input.read(bytes);
			return new String(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static byte[] getInputStreamByBytes(InputStream _input, int size) {
		try {
			byte[] bytes = new byte[size];
			_input.read(bytes);
			return bytes;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将字符串写入输出流中
	 * 
	 * @param output
	 *            输出流
	 * @param size
	 *            用几个字节描述 value所占用的字节数
	 * @param value
	 *            写入的值
	 */
	public static void setStringByOutputStream(DataOutputStream output,
			int size, String value) {
		try {
			byte[] b = value.getBytes();
			switch (size) {
			case 1:
				output.writeByte(b.length);// 写入uuid长度，占有一个字节
				break;
			case 2:
				output.writeShort(b.length);
				break;
			case 4:
				// System.out.println(b.length);
				output.writeInt(b.length);
				break;
			}

			output.write(b);// 写入uuid信息
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
